package com.etung.iot.demo.mqtt;

import com.etung.iot.demo.configs.TopicConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * @Classname MqttCallback
 * @Description 消费监听类
 */
@Component
@Slf4j
@MqttMessageListener(qos = MqttQoS.AT_MOST_ONCE,
        topic = {
                TopicConfig.REAL_DATA_TOPIC,
                TopicConfig.PLC_STATUS_TOPIC,
                TopicConfig.COLLECTOR_INFO_TOPIC,
                TopicConfig.ALARM_INFO_TOPIC,
                TopicConfig.VARIANT_REPLY_TOPIC,
                TopicConfig.DOWNLOAD_TOPIC,
                TopicConfig.SYS_TOPIC
        })
public class EmqxCallback implements MqttCallbackExtended {


    @Lazy
    @Autowired
    private EmqxService emqxService;

    @Override
    public void connectionLost(Throwable throwable) {
        log.info("mqtt断开连接--");
    }


    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        emqxService.subscribeCallback(topic, mqttMessage);
    }

    /**
     * 发布消息后，到达MQTT服务器，服务器回调消息接收
     *
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        // 消息到达 MQTT 代理时触发的事件
    }

    /**
     * 监听mqtt连接消息
     *
     * @param reconnect
     * @param serverURI
     */
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        log.info("mqtt已经连接！！");
        emqxService.subscribe();
    }
}
